﻿using System.Diagnostics;
using System.Net;

namespace AutoInternet.Utils;

public class InfoUtil
{
    public static string GetLocalIp()
    {
        ///获取本地的IP地址
        string AddressIP = string.Empty;
        foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
        {
            if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
            {
                AddressIP = _IPAddress.ToString();
            }
        }

        return AddressIP;
    }

    public static string GetMacByIpConfig()
    {
        List<string> macs = new List<string>();
        var runCmd = ExecuteInCmd("chcp 437&&ipconfig/all");
        foreach (var line in runCmd.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                     .Select(l => l.Trim()))
        {
            if (!string.IsNullOrEmpty(line))
            {
                if (line.StartsWith("Physical Address"))
                {
                    macs.Add(line.Substring(36));
                }
                else if (line.StartsWith("DNS Servers") && line.Length > 36 && line.Substring(36).Contains("::"))
                {
                    macs.Clear();
                }
                else if (macs.Count > 0 && line.StartsWith("NetBIOS") && line.Contains("Enabled"))
                {
                    return macs.Last();
                }
            }
        }

        return macs.FirstOrDefault();
    }

    public static string ExecuteInCmd(string cmdline)
    {
        using (var process = new Process())
        {
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            process.StandardInput.AutoFlush = true;
            process.StandardInput.WriteLine(cmdline + "&exit");

            //获取cmd窗口的输出信息  
            string output = process.StandardOutput.ReadToEnd();

            process.WaitForExit();
            process.Close();

            return output;
        }

    }
}